package com.feeling.oafeeling.controller;

import com.alibaba.fastjson.JSONObject;
import com.feeling.oafeeling.common.pojo.AjaxResult;
import com.feeling.oafeeling.mapper.UserRoleMapper;
import com.feeling.oafeeling.pojo.vo.PasswordUpdateVo;
import com.feeling.oafeeling.pojo.SysPermission;
import com.feeling.oafeeling.pojo.SysRole;
import com.feeling.oafeeling.pojo.SysUser;
import com.feeling.oafeeling.service.ISysUserService;
import com.feeling.oafeeling.service.impl.SysPermissionService;
import com.feeling.oafeeling.utils.util.IpUtil;
import com.feeling.oafeeling.utils.util.RedisPreEnum;
import com.feeling.oafeeling.utils.util.RedisUtil;
import com.feeling.oafeeling.utils.util.anno.PassToken;
import com.feeling.oafeeling.utils.util.service.TokenService;
import com.feeling.oafeeling.utils.util.sign.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Resource
    private ISysUserService userService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    TokenService tokenService;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Resource
    private RedisUtil redisUtil;
    //登录
    @ApiOperation(value = "登录")
    @PassToken(required = true)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUser user, HttpServletRequest request){
        JSONObject jsonObject=new JSONObject();
        //根据用户名查询用户信息
        System.out.println(Md5Utils.hash(user.getPassword()));
        SysUser userForBase=userService.findByUsername(user);
        String ipAddr = IpUtil.getRemoteAddr(request);
        if(userForBase==null){
            return AjaxResult.error(0,"登录失败,用户不存在");
        }else {
            if (userForBase.getStatus()==0){
                return AjaxResult.error("该账号已被禁用,请联系管理员");
            }
            if (!userForBase.getPassword().equals(Md5Utils.hash(user.getPassword()))){
                return AjaxResult.error(0,"登录失败,密码错误");
            }else {

                String token = tokenService.getToken(userForBase);
                String key = RedisPreEnum.JWT_TOKEN_PRE.getPre()+userForBase.getUserId();
                Set<String> keys = redisUtil.keys(key+"*");
                if (CollectionUtils.isEmpty(keys)){
                    redisUtil.set(userForBase.getUserId(),userForBase);
                    redisUtil.set(key+ipAddr,userForBase,RedisPreEnum.JWT_TOKEN_PRE.getExpired());
                }
                else {
                    if (redisUtil.get(key+ipAddr)==null){
                        return AjaxResult.error(0,"登录失败,账号已经在异地登陆");
                    }
//                    //请空之前的key
//                    for (String k:keys) {
//                        redisUtil.del(k);
//                    }
//                    //重新设置key
//                    redisUtil.set(key+ipAddr,userForBase,RedisPreEnum.JWT_TOKEN_PRE.getExpired());
                }

                jsonObject.put("id",userForBase.getUserId());
                jsonObject.put("username",userForBase.getUserName());
                jsonObject.put("ip",userForBase.getLoginIp());
                jsonObject.put("email",userForBase.getEmail());
                jsonObject.put("phoneNumber",userForBase.getPhonenumber());
                jsonObject.put("token",token);
                userForBase.setLoginIp(ipAddr);
//                if (userForBase.getLoginIp()==null){
//                    userForBase.setLoginIp(ipAddr);
//                    return AjaxResult.error("您是第一次登录，请修改密码",jsonObject);
//                }
                return AjaxResult.success("登录成功", jsonObject);


            }
        }
    }

    @GetMapping("/info")
    public AjaxResult getUserInfo(HttpServletRequest httpServletRequest){
//        JSONObject jsonObject= new JSONObject();
        String token = httpServletRequest.getHeader("Access-Token");
        //当前ip
//        String ipAddr = IpUtil.getIpAddr(httpServletRequest);

        String ipAddr = IpUtil.getRemoteAddr(httpServletRequest);
        //当前时间
        Date date = new Date(System.currentTimeMillis());
        Long userId = tokenService.verifyToken(token);
        SysUser user = userService.findUserAndRoleById(userId);
        SysUser userByBase = userService.findFromId(userId);
        if (userByBase.getLoginIp()== null || "".equals(userByBase.getLoginIp())){
            userByBase.setLoginDate(date);
            userService.updateUser(userByBase);
            user.setLoginState(true);
        }
        else {
            userByBase.setLoginIp(ipAddr);
            userByBase.setLoginDate(date);
            userService.updateUser(userByBase);
            user.setLoginState(false);
        }
        Set<String> permissions = sysPermissionService.getMenuPermission(user);
        Set<SysPermission> sysPermissions = new HashSet<>();
        for (String permission : permissions) {
            SysPermission sysPermission = new SysPermission();
            sysPermission.setRoleId(user.getRole().getId());
            sysPermission.setPermissionId(permission);
            sysPermissions.add(sysPermission);
        }
        SysRole role = user.getRole();
        role.setPermissions(sysPermissions);
        user.setPermissions(permissions);
        return AjaxResult.success("查询成功",user);
    }

//    @GetMapping("/isFirstLogin")
//    public boolean isFirstLogin(HttpServletRequest request){
//        //当前ip
//        String ipAddr = IpUtil.getIpAddr(request);
//        //当前时间
//        Date date = new Date(System.currentTimeMillis());
//
//        String token = request.getHeader("Access-Token");
//        Long userId = tokenService.verifyToken(token);
//        SysUser userByBase = userService.findFromId(userId);
//        if (userByBase.getLoginIp()==null||userByBase.getLoginIp()==""){
//            userByBase.setLoginIp(ipAddr);
//            userByBase.setLoginDate(date);
//            userService.updateUser(userByBase);
//            return true;
//        }
//        else {
//            userByBase.setLoginIp(ipAddr);
//            userByBase.setLoginDate(date);
//            userService.updateUser(userByBase);
//            return false;
//        }
//    }
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PutMapping("/updateDefaultPwd")
    public AjaxResult updateDefaultPwd(@RequestBody PasswordUpdateVo passwordUpdateVo){
        String userId = passwordUpdateVo.getUserId();
        SysUser userByBase = userService.findFromId(Long.parseLong(userId));
        userByBase.setPassword(Md5Utils.hash(passwordUpdateVo.getNewPassword()));
        userByBase.setLoginIp(null);
        if (userService.updateUser(userByBase)){
            return AjaxResult.success("修改成功");
        }
        else {
            return AjaxResult.error("修改失败");
        }
    }

    @ApiOperation(value = "密码修改")
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(HttpServletRequest httpServletRequest, @RequestBody PasswordUpdateVo passwordUpdateVo){
        String token = httpServletRequest.getHeader("Access-Token");
        String ipAddr = IpUtil.getRemoteAddr(httpServletRequest);
        Long userId = tokenService.verifyToken(token);
        SysUser userByBase = userService.findFromId(userId);
//        if (Md5Utils.hash(passwordUpdateVo.getNewPassword()).equals(Md5Utils.hash("123456"))){
//            userByBase.setPassword(Md5Utils.hash(passwordUpdateVo.getNewPassword()));
//            userByBase.setLoginIp(null);
//            if (userService.updateUser(userByBase)){
//                return AjaxResult.success("修改成功");
//            }
//            else {
//                return AjaxResult.error("修改失败");
//            }
//        }
        if (Md5Utils.hash(passwordUpdateVo.getOldPassword()).equals(userByBase.getPassword())){
            userByBase.setPassword(Md5Utils.hash(passwordUpdateVo.getNewPassword()));
            userByBase.setLoginIp(ipAddr);
            if (userService.updateUser(userByBase)){
                return AjaxResult.success("修改成功");
            }
            else {
                return AjaxResult.error("修改失败");
            }
        }else {
            return AjaxResult.error("密码输入错误，亲重新输入");
        }

    }

    //登出
    @ApiOperation(value = "登出")
    @PassToken(required = true)
    @PostMapping("/logout")
    public AjaxResult logOut(HttpServletRequest request){
        String token = request.getHeader("Access-Token");
        String ipAddr = IpUtil.getRemoteAddr(request);
        Long userId = tokenService.verifyToken(token);
        String key = RedisPreEnum.JWT_TOKEN_PRE.getPre()+userId;
        if (redisUtil.get(key+ipAddr)!=null){
            redisUtil.del(key+ipAddr);
        }
//        String ipAddr = IpUtil.getIpAddr(request);
//        SysUser userByBase = userService.findByUsername(user);
//        String key = RedisPreEnum.JWT_TOKEN_PRE.getPre()+userByBase.getUserId();
//        redisUtil.del(key+ipAddr);
        return AjaxResult.success("登出成功");
    }

    /**
     * 分页查询用户
     * @param currentPage
     * @param pageSize
     * @return List<SysUser>
     */
    @GetMapping("/1/5")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public AjaxResult findAllByPage(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize){
        System.out.println("test:********"+currentPage);
        System.out.println(pageSize);
        List<SysUser> byPage = userService.findByPage((currentPage - 1) * pageSize, pageSize, null);
        Integer userSize = userService.getUserSize();
        for (SysUser user: byPage){
            user.setTotal(userSize);
        }
        if (byPage == null){
            return AjaxResult.error("查询失败");
        }

        System.out.println(AjaxResult.success("查询成功",byPage));
        return AjaxResult.success("查询成功",byPage);
    }

//    public AjaxResult findOne(@RequestParam(value = "userId") Long userId,
//                              @RequestParam(value = "nickName") String nickName,
//                              @RequestParam(value = "deptName") String deptName,
//                              @RequestParam(value = "status") Integer status){
//        System.out.println(userId);
//        System.out.println(nickName);
//        System.out.println(deptName);
//        System.out.println(status);

    /**
     * 条件筛选查询单个用户
     * @param user
     * @return List<SysUser>
     */
    @PostMapping ("/findOne")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public AjaxResult findOne(@RequestBody SysUser user)  {
        System.out.println(user);
        List<SysUser> userList = userService.findOne(user);
        Integer userSize = userService.getUserSize();
        for (SysUser one: userList){
            one.setTotal(userSize);
        }
        System.out.println(userList);
        if (userList == null){
            return AjaxResult.error("没有该用户");
        }
        return AjaxResult.success("查询成功", userList);
    }

    /**
     * 新建用户
     * @param user
     * @return Boolean
     */
    @PostMapping("/insert")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public AjaxResult insertUser(@RequestBody SysUser user){
        System.out.println("**********************" + user);
        if (userService.findFromId(user.getUserId()) != null){
            return AjaxResult.error("已存在该用户");
        }
        user.setUserName(user.getNickName());
        user.setDeptName(userService.selectDeptNameById(user.getDeptId()));
        user.setPassword(Md5Utils.hash("000000"));
        System.out.println("**************==========="+user);
        userService.save(user);
        SysUser userByBase = userService.findByUsername(user);
        Long userId = userByBase.getUserId();
        userRoleMapper.insert(userId,Long.parseLong(user.getRoleId()));
//        userService.updatePasswordForUser(user, Md5Utils.hash("123456"));
//        userService.defaultUserNameSet(user);
        return AjaxResult.success("新建成功");
    }

    /**
     * 编辑用户信息
     * @param user
     * @return Boolean
     */
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public AjaxResult updateUser(@RequestBody SysUser user){
        if (userService.findFromId(user.getUserId()) == null){
            return AjaxResult.error("不存在该用户信息");
        }
//        return AjaxResult.success("更新成功", userService.updateInstitutionForUser(user,institutionName));
        userService.updateFromId(user);
        return AjaxResult.success("更新成功");
    }





}